package com.example.seakdreamandroid.sleep;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.example.seakdreamandroid.Constant;
import com.example.seakdreamandroid.R;
import com.example.seakdreamandroid.entity.User;
import com.example.seakdreamandroid.sleep.entity.ClockInfo;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class AlarmItemDetail extends AppCompatActivity {

    private TextView aidSelectTime,tvRingBellTime,aidHead;
    private EditText editNote;
    private Button aidDel,aidSure;
    private ImageButton aidReturn;
    private int flag;
    private RelativeLayout relRingTime;
    private LinearLayout allLayout;
    private TimePickerView pvTime;
    //选的的时间
    private String time;
    //选择提醒的周期
    private int cycle;
    private User user;
    /**
     * 连接后端新加
     * @param savedInstanceState
     */
    private ClockInfo clockInfo;
    private String str = "";
    private FormBody body;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.alarm_item_detail);

        //获取控件对象
        getViews();

        aidDel.setVisibility(View.VISIBLE);
        
        //获取Intent对象
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        flag = bundle.getInt("flag");
        switch (flag) {
            case 1:
                clockInfo = (ClockInfo) bundle.getSerializable("alarm");
                aidHead.setText("设置闹钟");
                editNote.setText(clockInfo.getMemo());
                aidSelectTime.setText(clockInfo.getTime());
                tvRingBellTime.setText(clockInfo.getRepeatSituation());
                break;
            case 2:
                clockInfo = (ClockInfo)bundle.getSerializable("prompt");
                aidHead.setText(clockInfo.getMemo());
                aidSelectTime.setText(clockInfo.getTime());
                tvRingBellTime.setText(clockInfo.getRepeatSituation());
                break;
            case 3:
                aidHead.setText("新建闹钟");
                aidDel.setVisibility(View.GONE);
                break;
        }
        //设置点击事件
        setListener();
    }

    private void setListener() {
        //删除闹钟
        aidDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deleteData();
            }
        });
        //保存
        aidSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (flag) {
                    case 1:
                        str = "editClock?";
                        clockInfo.setTime(aidSelectTime.getText().toString());
                        clockInfo.setMemo(editNote.getText().toString());
                        clockInfo.setRepeatSituation(tvRingBellTime.getText().toString());
                        clockInfo.setIfOpen(clockInfo.getIfOpen());
                        body= new FormBody.Builder()
                                .add("userId",clockInfo.getUserId())
                                .add("clockId",clockInfo.getClockId())
                                .add("time",clockInfo.getTime())
                                .add("memo",clockInfo.getMemo())
                                .add("repeatSituation",clockInfo.getRepeatSituation())
                                .add("ifOpen", "1")
                                .build();
                        postAsync(str,body);
                        break;
                    case 3:
                        user = (User)getApplication();
                        System.out.println(user.getUserId());
                        str = "createClockInfo?";
                        clockInfo= (ClockInfo) getIntent().getExtras().getSerializable("add");
                        clockInfo.setUserId(user.getUserId());
                        clockInfo.setTime(aidSelectTime.getText().toString());
                        clockInfo.setMemo(editNote.getText().toString());
                        clockInfo.setRepeatSituation(tvRingBellTime.getText().toString());
                        clockInfo.setIfOpen(0);
                        body = new FormBody.Builder()
                                .add("userId",clockInfo.getUserId())
                                .add("time",clockInfo.getTime())
                                .add("memo",clockInfo.getMemo())
                                .add("repeatSituation",clockInfo.getRepeatSituation())
                                .add("ifOpen", "1")
                                .build();
                        postAsync(str,body);
                        break;
                }
            }
        });
        //返回按钮
        aidReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(AlarmItemDetail.this,AlarmClockAndPrompt.class);
                startActivity(intent);
            }
        });
        //修改闹钟时间 ---187
        aidSelectTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println("11");
                pvTime = new TimePickerView(AlarmItemDetail.this, TimePickerView.Type.HOURS_MINS);
                pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date) {
                        time = getTime(date);
                        aidSelectTime.setText(time);
                    }
                });
                aidSelectTime.setOnClickListener((v)->{
                    pvTime.show();
                });
            }
        });
        relRingTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectRemindCycle();
            }
        });
    }
    private String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        return format.format(date);
    }

    //删除
    private void deleteData() {
        AlertDialog.Builder builder = new AlertDialog.Builder(AlarmItemDetail.this);
        builder .setMessage("确定删除这个闹钟？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        str = "deleteClockById?";
                        System.out.println(clockInfo.getClockId());
                        body = new FormBody.Builder()
                                .add("clockId",clockInfo.getClockId())
                                .build();
                        postAsync(str,body);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    //保存后修改数据库内信息，跳转到闹钟界面
    private void postAsync(String s,FormBody body) {
        OkHttpClient okHttpClient = new OkHttpClient();
        //创建请求对象（Request）
        Request request = new Request.Builder()
                //设置
                .url(Constant.BASE_URL +"clock/"+s)
                .post(body)//设置请求方式为post，添加了请求体
                //创建Request对象
                .build();
        //发送请求，获取响应
        //(一个call对象对应一个response)
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okHttp","onfilure");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //修改用户界面，需要使用Handler或RunOnUiThread
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent= new Intent(AlarmItemDetail.this,AlarmClockAndPrompt.class);
                        startActivity(intent);
                    }
                });
            }
        });

    }

//选择重复响铃时间
    private void selectRemindCycle() {
        final SelectRemindCyclePopup fp = new SelectRemindCyclePopup(this);
        fp.showPopup(allLayout);
        fp.setOnSelectRemindCyclePopupListener(new SelectRemindCyclePopup
                .SelectRemindCyclePopupOnClickListener() {
            @Override
            public void obtainMessage(int flag, String ret) {
                switch (flag) {
                    // 星期一
                    case 0:
                        break;
                    // 星期二
                    case 1:
                        break;
                    // 星期三
                    case 2:
                        break;
                    // 星期四
                    case 3:
                        break;
                    // 星期五
                    case 4:
                        break;
                    // 星期六
                    case 5:
                        break;
                    // 星期日
                    case 6:
                        break;
                    // 确定
                    case 7:
                        int repeat = Integer.valueOf(ret);
                        tvRingBellTime.setText(parseRepeat(repeat, 0));
                        cycle = repeat;
                        fp.dismiss();
                        break;
                    case 8:
                        tvRingBellTime.setText("每天");
                        cycle = 0;
                        fp.dismiss();
                        break;
                    case 9:
                        tvRingBellTime.setText("只响一次");
                        cycle = -1;
                        fp.dismiss();
                        break;
                    default:
                        break;
                }
            }
        });
    }

    /**
     * @param repeat 解析二进制闹钟周期
     * @param flag   flag=0返回带有汉字的周一，周二cycle等，flag=1,返回weeks(1,2,3)
     * @return
     */
    public static String parseRepeat(int repeat, int flag) {
        String cycle = "";
        String weeks = "";
        if (repeat == 0) {
            repeat = 127;
        }
        if (repeat % 2 == 1) {
            cycle = "周一";
            weeks = "1";
        }
        if (repeat % 4 >= 2) {
            if ("".equals(cycle)) {
                cycle = "周二";
                weeks = "2";
            } else {
                cycle = cycle + "," + "周二";
                weeks = weeks + "," + "2";
            }
        }
        if (repeat % 8 >= 4) {
            if ("".equals(cycle)) {
                cycle = "周三";
                weeks = "3";
            } else {
                cycle = cycle + "," + "周三";
                weeks = weeks + "," + "3";
            }
        }
        if (repeat % 16 >= 8) {
            if ("".equals(cycle)) {
                cycle = "周四";
                weeks = "4";
            } else {
                cycle = cycle + "," + "周四";
                weeks = weeks + "," + "4";
            }
        }
        if (repeat % 32 >= 16) {
            if ("".equals(cycle)) {
                cycle = "周五";
                weeks = "5";
            } else {
                cycle = cycle + "," + "周五";
                weeks = weeks + "," + "5";
            }
        }
        if (repeat % 64 >= 32) {
            if ("".equals(cycle)) {
                cycle = "周六";
                weeks = "6";
            } else {
                cycle = cycle + "," + "周六";
                weeks = weeks + "," + "6";
            }
        }
        if (repeat / 64 == 1) {
            if ("".equals(cycle)) {
                cycle = "周日";
                weeks = "7";
            } else {
                cycle = "每天";
                weeks = weeks + "," + "7";
            }
        }

        return flag == 0 ? cycle : weeks;
    }


    private void getViews() {
        aidSelectTime = findViewById(R.id.aid_selectTime);
        editNote = findViewById(R.id.edit_note);
        aidHead = findViewById(R.id.aid_head);
        aidDel = findViewById(R.id.aid_del);
        aidSure = findViewById(R.id.aid_sure);
        aidReturn = findViewById(R.id.aid_return);
        relRingTime = findViewById(R.id.rel_ringBellTime);
        allLayout = findViewById(R.id.all_layout);
        tvRingBellTime = findViewById(R.id.tv_ringBellTime);
    }
}